package com.ruoyi.project.remake.service.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.AuthUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IdCardUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.project.common.utils.DictUtils;
import com.ruoyi.project.remake.domain.*;
import com.ruoyi.project.remake.domain.constant.InitConstant;
import com.ruoyi.project.remake.domain.dto.CaseMainDto;
import com.ruoyi.project.remake.domain.dto.TCaseMainExcel;
import com.ruoyi.project.remake.domain.enmu.RemakeSourceState;
import com.ruoyi.project.remake.domain.enmu.RemakeStatusState;
import com.ruoyi.project.remake.domain.test.Details;
import com.ruoyi.project.remake.domain.test.Query;
import com.ruoyi.project.remake.domain.thrid.ThridCase;
import com.ruoyi.project.remake.domain.vo.CaseMainVo;
import com.ruoyi.project.remake.domain.vo.CopyCaseVo;
import com.ruoyi.project.remake.domain.vo.PrintMoney;
import com.ruoyi.project.remake.domain.vo.RemakeVo;
import com.ruoyi.project.remake.mapper.CaseMainThridMapper;
import com.ruoyi.project.remake.service.*;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysDictDataService;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.http.client.HttpClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.remake.mapper.TCaseMainMapper;

/**
 * 病例主表Service业务层处理
 *
 * @author 孙山伟
 * @date 2020-12-14
 */
@Service
public class TCaseMainServiceImpl implements ITCaseMainService {
    @Autowired
    private TCaseMainMapper tCaseMainMapper;
    @Autowired
    private CaseMainThridMapper caseMainThridMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ITRemakeService tRemakeService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private ITRemakeCaseDetailsService tRemakeCaseDetailsService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ICaseMainThridService caseMainThridService;

    @Autowired
    private IRemakeCaseDetailsThridService remakeCaseDetailsThridService;

    @Autowired
    private ISysConfigService configService;
    /**
     * 查询病例主表
     *
     * @param id 病例主表ID
     * @return 病例主表
     */
    @Override
    public CaseMainVo selectTCaseMainById(Long id) {
        TCaseMain caseMain=tCaseMainMapper.selectTCaseMainById(id);
        boolean is=IdCardUtil.isIdcard(caseMain.getIdentityCard());
        if(is){
            int now=IdCardUtil.year(new Date());
            int year=Integer.valueOf(caseMain.getIdentityCard().substring(6,10));
            caseMain.setAge(now-year+1);
        }
        CaseMainVo caseMainVo=new CaseMainVo();
        BeanUtils.copyProperties(caseMain,caseMainVo);
        caseMainVo.setDischargeTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,caseMain.getDischargeTime()));
        return caseMainVo;
    }

    /**
     * 查询病例主表列表
     *
     * @param tCaseMain 病例主表
     * @return 病例主表
     */
    @Override
    public List<TCaseMain> selectTCaseMainList(TCaseMain tCaseMain) {
        return tCaseMainMapper.selectTCaseMainList(tCaseMain);
    }

    /**
     * 新增病例主表
     *
     * @param tCaseMain 病例主表
     * @return 结果
     */
    @Override
    public int insertTCaseMain(TCaseMain tCaseMain) {
        tCaseMain.setCreateTime(DateUtils.getNowDate());
        return tCaseMainMapper.insertTCaseMain(tCaseMain);
    }

    /**
     * 修改病例主表
     *
     * @param tCaseMain 病例主表
     * @return 结果
     */
    @Override
    public int updateTCaseMain(TCaseMain tCaseMain) {
        tCaseMain.setUpdateTime(DateUtils.getNowDate());
        return tCaseMainMapper.updateTCaseMain(tCaseMain);
    }

    /**
     * 批量删除病例主表
     *
     * @param ids 需要删除的病例主表ID
     * @return 结果
     */
    @Override
    public int deleteTCaseMainByIds(Long[] ids) {
        return tCaseMainMapper.deleteTCaseMainByIds(ids);
    }

    /**
     * 删除病例主表信息
     *
     * @param id 病例主表ID
     * @return 结果
     */
    @Override
    public int deleteTCaseMainById(Long id) {
        return tCaseMainMapper.deleteTCaseMainById(id);
    }

    /**
     * 翻拍程序初始化翻拍程序
     *
     * @param tCaseMain
     * @return
     */
    @Override
    public RemakeVo creatTCaseMain(TCaseMain tCaseMain) {
        RemakeVo remakeVo = new RemakeVo();
        // tCaseMain.setCreateBy(AuthUtil.getRemake().getId().toString());
        tCaseMain.setRemakeName(tCaseMain.getUserName());
        tCaseMain.setCreateBy(tCaseMain.getUserId().toString());
        tCaseMain.setCreateTime(DateUtils.getNowDate());
        tCaseMain.setStatus(RemakeStatusState.WAIT_AUDIT.getValue().toString());
        tCaseMain.setSource(RemakeSourceState.REMAKE.getValue().toString());
        TRemake sysUser = tRemakeService.selectTRemakeById(tCaseMain.getUserId());
        tCaseMain.setRemakeName(null == sysUser ? "系统用户" : sysUser.getRemakeName());
        tCaseMain.setPrintNumber(0L);
        tCaseMainMapper.insertTCaseMain(tCaseMain);
        String filePath = RuoYiConfig.getImagedPath() + "/" + tCaseMain.getCardNumber();
        File file = new File(filePath);
        if (!file.exists()) {//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        remakeVo.setId(tCaseMain.getId());
        remakeVo.setUrl(tCaseMain.getCardNumber());
        return remakeVo;
    }

    @Override
    public  List<CopyCaseVo> selectTCaseMainFrontList(CaseMainDto caseMainDto) {
        List<CopyCaseVo> copyCaseVoList= null;
      /*  if(RemakeSourceState.HOSPITAL.getValue().toString().equals(caseMainDto.getType())){//如果需要对接第三方
            copyCaseVoList=caseMainThridMapper.selectTCaseMainFrontList(caseMainDto);
        }else{*/
            copyCaseVoList= tCaseMainMapper.selectTCaseMainFrontList(caseMainDto);

      /*  }*/
        List<SysDictData> dictDataList=dictDataService.selectDictDataByType(InitConstant.APPROLVAL_STATUS);
        for(CopyCaseVo vo:copyCaseVoList){
            vo.setStatus(DictUtils.getDiactLabel(dictDataList,vo.getStatus()));
        }
        return copyCaseVoList;
    }

    /**
     * 将第三方查询结果转化为前台展示内容
     * @param dataList
     * @return
     */
    public void  coverCopyList(String dataList) {
        List<SysDictData> dictDataList=dictDataService.selectDictDataByType(InitConstant.PRINT_CLASS);
        List<ThridCase> thridCaseList = JSON.parseArray(dataList, ThridCase.class);
        //按照病历号进行去重复操作
        Collections.reverse(thridCaseList);
        ArrayList<ThridCase> collect = thridCaseList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                Comparator.comparing(ThridCase::getCardNumber)
        )), ArrayList::new));
        if(ObjectUtil.isNotEmpty(collect)){
            for(ThridCase thridCase:collect){
                TCaseMain thrid=new TCaseMain();
                //病历号
                thrid.setCardNumber(thridCase.getCardNumber());
               List<TCaseMain>  caseMainThridList=  tCaseMainMapper.selectTCaseMainList(thrid);
             if(ObjectUtil.isEmpty(caseMainThridList)&&caseMainThridList.size()==0){

                 //身份照
                 thrid.setIdentityCard(thridCase.getIdCard());
                 //身份照
                 thrid.setCardId(thridCase.getIdCard());
                 //住院号
                 thrid.setAdmissionNumber(thridCase.getPatinetId());

                 try {
                     //入院时间
                     thrid.setAdmissionTime(DateUtils.parseDate(thridCase.getInHospital(),DateUtils.YYYY_MM_DD_HH_MM_SS));
                     //出院时间
                     thrid.setDischargeTime(DateUtils.parseDate(thridCase.getOutHopstital(),DateUtils.YYYY_MM_DD_HH_MM_SS));
                 } catch (ParseException e) {
                     e.printStackTrace();
                 }
                 thrid.setBeDepartment(thridCase.getKs());
                 thrid.setLeaveDepartment(thridCase.getKs());
                 //来源医院
                 thrid.setSource(RemakeSourceState.HOSPITAL.getValue().toString());
                 tCaseMainMapper.insertTCaseMain(thrid);
                 int i=1;
                 for(ThridCase  case1:thridCaseList ){
                     TRemakeCaseDetails  detailsThrid=new TRemakeCaseDetails();
                     detailsThrid.setCaseMainId(thrid.getId());
                     detailsThrid.setImgXh(i++);
                     detailsThrid.setStatus(RemakeStatusState.PASS_AUDIT.getValue().toString());
                     //
                     detailsThrid.setClassType(getClsssType(dictDataList,thrid.getMedicalCardId()));
                     //base64 转化到服务器上某一个路径路径，
                     Long time=System.currentTimeMillis();
                     String tmpFilePath=RuoYiConfig.getThridfile()+"/"+case1.getCardNumber()+time+InitConstant.SUB_THRID_TYPE;
                     try {
                         FileUtils.strToFile(case1.getFileAddress(),tmpFilePath);
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                     // 上传文件路径
                     String filePath = RuoYiConfig.getUploadPath();
                     // 上传并返回新文件名称
                     File file=new File(tmpFilePath);
                     String fileName = null;
                     try {
                         //将File文件转化为MultipartFile,并进行上传
                         fileName = FileUploadUtils.upload(filePath, FileUtils.getMultipartFile(file));
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                     detailsThrid.setImgName(time+InitConstant.SUB_THRID_TYPE);
                     detailsThrid.setImgPath(configService.selectConfigByKey(InitConstant.PRO_IMG_KEY) + "/" + fileName);
                     //为了服务器空间，用完之后删掉原有的垃圾文件
                     FileUtils.deleteFile(tmpFilePath);
                     tRemakeCaseDetailsService.insertTRemakeCaseDetails(detailsThrid);
                 }

             }
            }
        }

    }

    private String getClsssType(List<SysDictData> dictDataList, String medicalCardId) {
        if(ObjectUtil.isNotNull(dictDataList)){
            return  null;
        }
        for(SysDictData data:dictDataList){
            if(medicalCardId.equals(data.getCssClass())){
                return data.getDictValue();
            }
        }
return null;
    }

    @Override
    public TCaseMain selectByCarNumber(String carNumber) {
        return tCaseMainMapper.selectByCarNumber(carNumber);
    }

    @Override
    public List<TCaseMain> selectSelfFrontList(TCaseMain tCaseMain) {
        return tCaseMainMapper.selectSelfFrontList(tCaseMain);
    }

    /**
     * 根据病历号计算打印费用
     *
     * @param cardNumber
     * @return
     */
    @Override
    public PrintMoney getTotileMoney(String cardNumber) {
        PrintMoney printMoney = new PrintMoney();
        TCaseMain tCaseMain = tCaseMainMapper.selectByCarNumber(cardNumber);

        if (null == tCaseMain) {
            return printMoney;
        }
        TRemakeCaseDetails details = new TRemakeCaseDetails();
        details.setCaseMainId(tCaseMain.getId());
        List<TRemakeCaseDetails> remakeCaseDetails = tRemakeCaseDetailsService.selectTRemakeCaseDetailsList(details);
        if (remakeCaseDetails.isEmpty()) {
            return printMoney;
        }
        List<SysDictData> sysDictDataCaseLit = sysDictDataService.selectDictDataByType(Constants.CASE_CLASS);
        for (int i = 0; i < remakeCaseDetails.size(); i++) {
            for (SysDictData sysDictData : sysDictDataCaseLit) {
                String type = remakeCaseDetails.get(i).getClassType();
                if (type.equals(sysDictData.getDictValue())) {
                    if (sysDictData.getRemark().equals(InitConstant.IS_PRINT)) {
                        remakeCaseDetails.remove(i);
                        i--;
                        break;
                    }
                }
            }
        }
        Integer pageSize = remakeCaseDetails.size();
        BigDecimal pageBig = new BigDecimal(pageSize);
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataByType(Constants.PRINT_FEE);
        if (sysDictDataList.size() == 0) {
            return printMoney;
        }
        BigDecimal parintFee = new BigDecimal(sysDictDataList.get(0).getDictValue());
        BigDecimal totalFee = pageBig.multiply(parintFee).setScale(2, RoundingMode.HALF_UP);
        printMoney.setTotleParper(pageSize);//纸张数量
        printMoney.setReceivables(totalFee.toString());//应收款
        return printMoney;
    }

    @Override
    public List<TCaseMain> queryByParam(Query query) {
        List<TCaseMain> tCaseMainList = Lists.newArrayList();
        SysDictData dictData = new SysDictData();
        dictData.setDictType(Constants.CASE_CLASS);
        List<SysDictData> list = sysDictDataService.selectDictDataList(dictData);
        TCaseMain tCaseMain = selectByCarNumber(query.getCardNumber());
        List<Details> detailsList = Lists.newArrayList();
        if (null != tCaseMain) {
            for (SysDictData sysDictData : list) {
                Details details = new Details();
                details.setCaseMainId(tCaseMain.getId());
                details.setClassType(sysDictData.getDictLabel());
                details.setClassId(sysDictData.getDictValue());
                List<TRemakeCaseDetails> tRemakeCaseDetails = tRemakeCaseDetailsService.remakeDetails(tCaseMain.getId(), sysDictData.getDictValue());
                List<String> agentIds = tRemakeCaseDetails.stream().map(TRemakeCaseDetails::getImgPath).collect(Collectors.toList());
                details.setImgList(agentIds);
                detailsList.add(details);

                tCaseMain.setDetailsList(detailsList);
                tCaseMainList.add(tCaseMain);
            }
        }
        return tCaseMainList;
    }

    @Override
    public List<TCaseMain> selectTCaseMainFrontAllList(TCaseMain tCaseMain) {
        return tCaseMainMapper.selectTCaseMainFrontAllList(tCaseMain);
    }

    @Override
    public String importExcel(List<TCaseMainExcel> farmerExcelList) {
        for (TCaseMainExcel tCaseMainExcel : farmerExcelList) {
            TCaseMain tCaseMain = new TCaseMain();
            tCaseMain.setCardNumber(tCaseMainExcel.getCardNumber());
            try {
                tCaseMain = tCaseMainMapper.selectByCarNumber(tCaseMainExcel.getCardNumber());
            } catch (Exception e) {
                continue;
            }
            try{
            if (ObjectUtil.isNull(tCaseMain)) {
                tCaseMain = new TCaseMain();
                BeanUtils.copyProperties(tCaseMainExcel, tCaseMain);
                if (tCaseMain.getSex().equals("2")) {
                    tCaseMain.setSex("女");
                    tCaseMain.setPatientsGender("女");
                } else {
                    tCaseMain.setSex("男");
                    tCaseMain.setPatientsGender("男");
                }
                tCaseMain.setIdentityCard(tCaseMain.getCardId());
                tCaseMain.setSource("0");
                tCaseMain.setStatus("0");
                tCaseMain.setWeight("0");
                tCaseMain.setHeight("0");
                tCaseMain.setCreateTime(new Date());
                tCaseMain.setCreateBy("1");
                tCaseMain.setBirthday(DateUtils.parseDate(tCaseMainExcel.getBirthday()));

                tCaseMainMapper.insertTCaseMain(tCaseMain);
            }
            }catch (Exception e){
                continue;
            }
        }
        return null;
    }


}
